var page = 1;

$(document).ready(function() {
	displayFaculty();
	displayProject();
	var currentUrl = window.location.href;
	if(currentUrl.indexOf('#') != -1){
		page = currentUrl.slice(currentUrl.indexOf('#') + 1);
	}
	displayNews(page);
	getCountNews(page);
});

$(window).bind('hashchange', function() {
	location.reload();
});

function displayNews(){
	var params = {
		action: 'getByLimit',
		fromNews: LIMIT_NEWS * (parseInt(page) - 1),
		toNews: LIMIT_NEWS
	};
	sendRequest(URL_NEWS, 'GET', params, function(res){
		var data = JSON.parse(res);
		if(data[0]){
			$('#firstNew').append(drawBigNew(data[0]));
		}
		for(var index = 1; index < data.length; index+=2){
			var tempDiv = drawDiv('row form-group');
			if(data[index]){
				tempDiv.append(drawBigNew(data[index]));
			}
			if(data[index+1]){
				tempDiv.append(drawBigNew(data[index+1]));
			}
			$('#newList').append(tempDiv);
		}
	}, function(err){
	});
}

function getCountNews(currentPage){
	var params = {
		action: 'getCountRow'
	};
	sendRequest(URL_NEWS, 'GET', params, function(res){
		var data = JSON.parse(res);
		var countPage = Math.round(data.countRow / LIMIT_NEWS);
		if(data.countRow % LIMIT_NEWS > 0 && data.countRow % LIMIT_NEWS < LIMIT_NEWS/2){
			countPage++;
		}
		$('#pageList').html('');
		if(currentPage > countPage){
			currentPage = countPage;
		}
		if(currentPage > 5){
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage - 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage)));
			if(currentPage + 1 < countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage + 1)));
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			} else if(currentPage + 1 == countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			}
		} else {
			for(var index = 1; index <= countPage; index++){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, index)));
			}
		}
	}, function(err){
	});
}